package org.pfc.porlapatilla.controllers;

import java.util.List;

import org.pfc.porlapatilla.model.Category;
import org.pfc.porlapatilla.services.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 
 * @author jorgepolobermudez
 * 
 */
@Controller
@RequestMapping("/categories")
public class CategoryController {

    private static final Logger logger = LoggerFactory
	    .getLogger(CategoryController.class);

    /**
     * The CategoryService instance.
     */
    @Autowired
    private CategoryService categoryService;
    
    /**
     * Find all stored categories
     * @return The list of all categories
     */
    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody List<Category> getCategories() {
	logger.info("Retrieving all categories");
	return categoryService.findAll();
    }

    /**
     * Find stored category by name.
     * 
     * @param name
     *            The category name.
     * @return The found category.
     */
    @RequestMapping(value = "/name/{name}", method = RequestMethod.GET)
    public @ResponseBody
    Category getCategoryByName(@PathVariable String name) {
	logger.info("Retrieving category by name + [" + name + "]");
	return categoryService.findByName(name);
    }

    /**
     * Create a new <strong>category</strong>.
     * 
     * @param The
     *            category to store.
     * @return The new <strong>category</strong>'s id.
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public @ResponseBody
    String addCategory(@RequestBody Category category) {
	return categoryService.store(category);
    }

    /**
     * Update an <strong>category</strong>.
     * 
     * @param category
     *            The <strong>category</strong> to update.
     * @return The updated <strong>category</strong> id.
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public @ResponseBody
    String updateCategory(@RequestBody Category category) {
	return categoryService.store(category);
    }

}
